package com.seanliao.nav.util;


import com.seanliao.nav.security.MyUserDetails;
import jakarta.servlet.http.HttpSession;
import lombok.experimental.UtilityClass;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;

@UtilityClass
public class SecurityUtil {

    /**
     * 设置当前用户
     */
    public void setCurrentUser(HttpSession httpSession, MyUserDetails myUserDetails) {
        // 会话中设置一份
        httpSession.setAttribute("userDetails", myUserDetails);
        // spring security也要设置一分
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(myUserDetails, myUserDetails.getPassword(), myUserDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    /**
     * 清除当前用户
     */
    public void clearCurrentUser(HttpSession httpSession){
        // 删除会话中的
        httpSession.removeAttribute("userDetails");
    }

    /**
     * 获取当前用户，从Session中获取
     */
    public MyUserDetails getCurrentUser(HttpSession httpSession) {
        Object userDetails = httpSession.getAttribute("userDetails");
        if (userDetails instanceof MyUserDetails myUserDetails) {
            return myUserDetails;
        } else {
            return null;
        }
    }

    /**
     * 获取当前用户，从Security上下文中获取
     */
    public MyUserDetails getCurrentUser() {
        Object userDetails = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (userDetails instanceof MyUserDetails myUserDetails) {
            return myUserDetails;
        } else {
            return null;
        }
    }

}
